package com.emperor.category.app;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Expression;

import com.emperor.cashier.app.CashierAppCtrl;
import com.emperor.category.logic.Category;
import com.emperor.category.logic.CategoryModel;
import com.emperor.core.app.App;
import com.emperor.core.app.AppBase;
import com.emperor.core.app.AppConstant;
import com.emperor.course.app.CourseAppCtrl;
import com.emperor.inventory.app.InventoryAppCtrl;
import com.emperor.treatment.app.TreatmentAppCtrl;
import com.emperor.util.HibernateUtil;
import com.swtdesigner.SWTResourceManager;

public class CategoryAppNew extends AppBase implements App {

	protected Shell shell;
	public static Logger log = Logger.getLogger(CategoryAppNew.class);
	private Integer type;	

	public CategoryAppNew() {
		super();
	}

	public CategoryAppNew(Map<String, Object> params) {
		super();
		this.params = params;
	}

	/**
	 * Launch the application
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			CategoryAppNew window = new CategoryAppNew();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window
	 */
	public void open() {
		final Display display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
	}

	/**
	 * Create contents of the window
	 */
	protected void createContents() {
		shell = new Shell();
		shell.setBackgroundMode(SWT.INHERIT_FORCE);
		shell.setBackgroundImage(SWTResourceManager.getImage(
				CategoryAppNew.class, "/img/main.jpg"));
		shell.setImage(SWTResourceManager.getImage(CategoryAppNew.class,
				"/img/iMac OSX.png"));
		shell.setSize(1000, 700);
		shell.setText("New Category");

		initScreen(shell, getParams());

		final Composite composite = new Composite(shell, SWT.NONE);
		composite.setBackgroundMode(SWT.INHERIT_DEFAULT);
		composite.setBounds(0, 50, 992, 362);

		final Label messageLabel = new Label(composite, SWT.NONE);
		messageLabel
				.setText("Please key in the details for New Category and click Save.");
		messageLabel.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		messageLabel.setBounds(10, 0, 872, 20);

		final Label categoryNameLabel = new Label(composite, SWT.NONE);
		categoryNameLabel.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		categoryNameLabel.setText("Name");
		categoryNameLabel.setBounds(10, 29, 110, 20);

		final Label categoryNameLabel_1 = new Label(composite, SWT.NONE);
		categoryNameLabel_1.setBounds(10, 76, 110, 20);
		categoryNameLabel_1.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		categoryNameLabel_1.setText("Description");

		final Text text = new Text(composite, SWT.BORDER);
		text.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		text.setToolTipText("cat_name");
		text.setBounds(144, 26, 506, 30);

		final Text text_1 = new Text(composite, SWT.WRAP | SWT.V_SCROLL
				| SWT.MULTI | SWT.BORDER);
		text_1.setBounds(144, 73, 506, 159);
		text_1.setToolTipText("cat_desc");
		text_1.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));

		final Button saveButton = new Button(composite, SWT.NONE);
		saveButton.setLocation(144, 238);
		saveButton.setSize(75, 30);
		saveButton.setImage(SWTResourceManager.getImage(CategoryAppNew.class,
				"/img/Save.png"));
		saveButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				try {
					Category category = new CategoryModel();

					type = (Integer)getParams().get(CategoryAppCtrl.CATEGORY_TYPE);
					if (type == null) {
						type = Category.TYPE_PRODUCT;
					}
					
					category = (Category) setModel(composite, "cat", category);
					log.debug(category.getClass().getSimpleName() + " : "
							+ category.getValues().toString());

					List<String> errors = validateForm(category);
					if (errors.isEmpty()) {
						category = (Category) preAdd(category, getParams());						

						category.setType(type);
						category.setStatus(AppConstant.STATUS_ACTIVE);

						int rowCount = doAdd(category);

						if (rowCount == 1) {
							// getParams().put(CategoryAppCtrl.CATEGORY_MSG,
							// "New category added successfully.");
							message(getShell(), "Save Success.",
									"New category added successfully.");
							
							String[] ctrlAction = switchCtrlAction(type);
							getParams().put(AppConstant.APPCTRL,
									ctrlAction[0]);
							getParams().put(AppConstant.ACTION,
									ctrlAction[1]);
							getShell().close();
						} else {
							message(getShell(), "Save Error.",
									"Unable to add category.", SWT.ICON_ERROR
											| SWT.OK);
						}
					} else {
						message(getShell(), "Save Error.", errors.get(0),
								SWT.ICON_ERROR | SWT.OK);
					}
				} catch (Exception ex) {
					message(getShell(), "Save Error.", ex.getMessage(),
							SWT.ICON_ERROR | SWT.OK);
					log.error(ex.getMessage(), ex);
				}
			}
		});
		saveButton.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		saveButton.setText("Save");

		final Button saveButton_1 = new Button(composite, SWT.NONE);
		saveButton_1.setLocation(227, 238);
		saveButton_1.setSize(80, 30);
		saveButton_1.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				getShell().close();
			}
		});
		saveButton_1.setImage(SWTResourceManager.getImage(CategoryAppNew.class,
				"/img/Refresh.png"));
		saveButton_1.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		saveButton_1.setText("Reset");
		//
		
		type = (Integer)getParams().get(CategoryAppCtrl.CATEGORY_TYPE);
		if (type == null) {
			type = Category.TYPE_PRODUCT;
		}		
		String[] ctrlAction = switchCtrlAction(type);
		System.out.println(ctrlAction[0] + ctrlAction[1]);
		buildStandardMenu(getShell(), getParams(),
				ctrlAction[0], ctrlAction[1]);
	}	

	public static List<String> validateForm(Category category) {
		List<String> errors = new ArrayList<String>();

		if (StringUtils.isEmpty(category.getName())) {
			errors.add("Category name cannot be empty.");
		}

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();

		List<Category> categories = new ArrayList<Category>();
		Criteria cris = session.createCriteria(CategoryModel.class).add(
				Expression.eq(Category.FLD_NAME, category.getName())).add(
				Expression.eq(Category.FLD_STATUS, AppConstant.STATUS_ACTIVE));
		if (category.getId() != null) {
			cris.add(Expression.ne(Category.FLD_ID, category.getId()));
		}
		categories = cris.list();

		if (categories != null && !categories.isEmpty()) {
			errors.add("Duplicate category name. Please use another name.");
		}

		return errors;
	}

	private int doAdd(Category category) throws Exception {
		int rowCount = 0;
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		try {
			session.beginTransaction();

			session.save(category);
			log.debug(category.getClass().getSimpleName() + " : "
					+ category.getValues().toString());
			rowCount++;

			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			log.error(e.getMessage(), e);
			throw e;
		}
		return rowCount;
	}

	public Shell getShell() {
		return shell;
	}
	
	public static String[] switchCtrlAction(Integer type) {		
		String[] result = new String[]{"",""};
		result[0] = InventoryAppCtrl.INVENTORY_CTRL;
		result[1] = InventoryAppCtrl.INVENTORY_ENQ;
		switch(type) {
		case Category.TYPE_COURSE:
			result[0] = CourseAppCtrl.COURSE_CTRL;
			result[1] = CourseAppCtrl.COURSE_ENQ;
			break;
		case Category.TYPE_TREATMENT:
			result[0] = TreatmentAppCtrl.TREATMENT_CTRL;
			result[1] = TreatmentAppCtrl.TREATMENT_ENQ;
			break;
		default:
			break;
		}		
		return result;
	}

}
